package com.vonchange.common.cookie;

import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

/*

 * 2014.07.01 

 * */

public class CookieUtil {
	// 保存cookie时的cookieName
	private final static String cookieDomainName = "vonchange.user";
	// 加密cookie时的网站自定码

//	private final static String webKey = "haitao123*";
	// 设置cookie有效期一个月
	private final static Integer cookieMaxAge = 60 * 60 * 24 * 30;

	// 保存Cookie到客户端-------------------------------------------------------------------------
	public static void saveUserCookie(String  token, HttpServletResponse response) {
		// 将要被保存的完整的Cookie值
	    String cookieValue=token;//MD5Util.getMD5(userId+ System.currentTimeMillis());
		// 开始保存Cookie
		Cookie cookie = new Cookie(cookieDomainName, cookieValue);
		// 存两年(这个值应该大于或等于validTime)
		cookie.setMaxAge(cookieMaxAge);
		// cookie有效路径是网站根目录
		cookie.setPath("/");
		// 向客户端写入
		response.addCookie(cookie);

	}

	// 在Filter程序中调用该方法,

	public static String readUserCookie(HttpServletRequest request)  {
		// 根据cookieName取cookieValue
		Cookie cookies[] = request.getCookies();
		String cookieValue = null;
		if (cookies != null) {
			for (Cookie cookie : cookies) {
				if (cookieDomainName.equals(cookie.getName())) {
					cookieValue = cookie.getValue();
					break;
				}
			}
		}
		// 如果cookieValue为空,返回,
		if (cookieValue == null) {
			return null;
		}
		return cookieValue;
	}

	// 用户注销时,清除Cookie,在需要时可随时调用-----------------------------------------------------
	public static void clearUserCookie(HttpServletResponse response) {
		Cookie cookie = new Cookie(cookieDomainName, null);
		cookie.setMaxAge(0);
		cookie.setPath("/");
		response.addCookie(cookie);
	}

}